package booyah.web;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SecurityFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;

        String requestUri = httpRequest.getRequestURI().toLowerCase();

        if ((requestUri != null) && (requestUri.contains("/signout"))) {
            httpRequest.getSession().removeAttribute("user"); // Clear the signed in state
        }

        if ((requestUri != null) && (requestUri.contains("/styles") || requestUri.contains("/images") || requestUri.contains("/event/show")|| requestUri.contains("/user/form"))) {
            // We'll allow the user/form to pass through in order to enable user creation
        } else
        if ((requestUri != null) && !requestUri.contains("/login") && !requestUri.contains("/createaccount")) {
            HttpSession session = httpRequest.getSession(false);
            if (session == null || session.getAttribute("user") == null) {
                ((HttpServletResponse) response).sendRedirect("/controller/login");
                return;
            }
        }
        chain.doFilter(request, response);
    }

    public void destroy() {
    }
}
